﻿namespace Homework17_2_
{
    /// <summary>
    /// 计算samples(2).txt 文件中总体的年龄、身高的平均值，以及男生女生分别的平均值
    /// </summary>
    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public double Height { get; set; }
        public string Gender { get; set; }
    }

    internal class Program
    {
        //定义文件路径
        private const string FilePath = @"D:\samples(2).txt";
        static void Main(string[] args)
        {
            //确定文件路径
            string filepath = FilePath;

            //读取文件
            var lines = File.ReadAllLines(filepath);
            var persons = lines.Select(line =>
            {
                //根据逗号将字符串拆分为字符串序列
                var parts = line.Split(',');
                return new Person
                {
                    Id = int.Parse(parts[0]),
                    Name = parts[1],
                    Age = int.Parse(parts[2]),
                    Height = int.Parse(parts[4]),
                    Gender = parts[5],
                };
            }).ToList();

            //计算总体平均值
            double TAgeAverage = persons.Average(p => p.Age);
            double THeightAverage = persons.Average(p => p.Height);

            //使用GroupBy函数分组计算均值
            var GenderGroup = persons.GroupBy(p => p.Gender).Select(g => new
            {
                //按性别进行分组
                Gender = g.Key,

                //计算分组平均值
                AgeAverage = g.Average(p => p.Age),
                HeightAverage = g.Average(p => p.Height),
            }).ToList();

            //输出结果
            Console.WriteLine($"总体年龄均值：{TAgeAverage}");
            Console.WriteLine($"总体身高均值：{THeightAverage}");

            //分组均值
            foreach(var avg in GenderGroup)
            {
                Console.WriteLine($"{avg.Gender}年龄均值：{avg.AgeAverage}");
                Console.WriteLine($"{avg.Gender}身高均值：{avg.HeightAverage}");
            }
            
        }
    }
}
